/* 
 * Author: Vassilis
 */

#include "Tileset.h"
#include "Resource.h"
#include "ResourceManager.h"
#include <cstdlib>


Tileset::Tileset()
{
    m_tiles = NULL;
    m_firstGid = 0;
}


Tileset::Tileset(const Tileset &toCopy)
{
    m_tiles = NULL;

    if( toCopy.m_tiles )
    {
        m_tiles = toCopy.m_tiles;
        m_tiles->IncreaseReference( );
    }

    m_firstGid = toCopy.m_firstGid;
}


Tileset::~Tileset()
{
    if( m_tiles )
        m_tiles->DecreaseReference( );
}


bool Tileset::Open(const std::string& path, const std::string& file, int fgid, unsigned tilesWidth)
{
    m_firstGid = fgid;
    Resource<gl::Texture>*  resource = ResourceManager::GetInstance()->GetTexture(path.c_str(),file.c_str());
    //m_totalColumns = m_tiles->getResImage_ptr()->GetWidth()/tilesWidth;
    if( resource )
    {
        if( m_tiles )
        {
            m_tiles->DecreaseReference( );
        }

        m_tiles = resource;
    }

    return m_tiles != NULL;
}


int Tileset::GetFirstGid() const
{
    return m_firstGid;
}


unsigned Tileset::GetTotalColumns(int tilesWidth) const
{
    return  m_tiles->GetRawData( )->GetWidth( ) / tilesWidth;
}

const gl::Texture *Tileset::GetTexture() const
{
    return m_tiles->GetRawData( );
}

Resource<gl::Texture> *Tileset::GetResource() const
{
    return m_tiles;
}

Tileset &Tileset::operator =( const Tileset& toAssign )
{
    if( this != &toAssign )
    {
        if( m_tiles )
            m_tiles->DecreaseReference( );

        m_tiles = toAssign.m_tiles;

        m_tiles->IncreaseReference( );

        m_firstGid = toAssign.m_firstGid;
    }

    return *this;
}

